package com.service.lotterySystem.service.impl;

import com.service.config.utils.*;
import com.service.lotterySystem.dao.HelpInfoDao;
import com.service.lotterySystem.dao.JoinInfoDao;
import com.service.lotterySystem.dao.UserInfoDao;
import com.service.lotterySystem.dto.*;
import com.service.lotterySystem.entity.HelpInfo;
import com.service.lotterySystem.entity.JoinInfo;
import com.service.lotterySystem.entity.UserInfo;
import com.service.lotterySystem.service.HelpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author ：hjl
 * @date ：Created in 2022/01/14 14:42
 * @description：
 */
@Service
@Slf4j
public class HelpServiceImpl implements HelpService {
    @Resource
    private HelpInfoDao helpInfoDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private JoinInfoServiceImpl joinInfoService;
    @Resource
    private JoinInfoDao joinInfoDao;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 助力
     * @param helpInfoDto
     * @return
     */
    @Override
    @Transactional
    public Result help(UserDto userDto, HelpUserInfoDto helpInfoDto) {
        String userId = UserTokenManager.getUserId(helpInfoDto.getUserToken());
        if (redisUtil.exist(helpInfoDto.getUserToken()+userId)) {
            try {
                JoinInfo joinInfo = joinInfoDao.queryAllByUIdAndAId(userId,helpInfoDto.getAId());
                if (joinInfo == null) {
                    return Result.failure("您助力的用户取消参加活动或未参加活动");
                }
                if (joinInfo.getShareCount() == null) {
                    joinInfo.setShareCount(1);
                }else {
                    joinInfo.setShareCount(joinInfo.getShareCount()+1);
                }
                HelpInfo helpInfo = helpInfoDao.queryAllByUIdAndAId(helpInfoDto.getAId(), userDto.getId());//查询是否助力过该用户
                if (helpInfo != null) {
                    return Result.failure("您已为其他用户在此活动中助力,无法为此用户助力");
                }
                joinInfo.setJUpdateTime(new Date());
                int update = joinInfoDao.update(joinInfo);
                if (update > 0) {
                    UserInfo userInfo = JsonXMLUtils.json2obj(redisUtil.getValue(helpInfoDto.getUserToken() + userId), UserInfo.class);
                    HelpInfo helpInfo1 = new HelpInfo();
                    helpInfo1.setAId(helpInfoDto.getAId());
                    HelpInfo duplicate = duplicate(helpInfo1, joinInfo, userDto, userInfo);
                    helpInfoDao.insert(duplicate);
                    return Result.ok();
                }
                return Result.failure("助力失败，请重新助力");
            } catch (Exception e) {
                log.error("help:"+e.getMessage());
                return Result.ok();
            }
        }
        UserInfo userInfo = userInfoDao.queryById(userId);//查询数据库的用户
        if (userInfo != null) {
            try {
                JoinInfo joinInfo = joinInfoDao.queryAllByUIdAndAId(userId,helpInfoDto.getAId());
                if (joinInfo == null) {
                    return Result.failure("您助力的用户取消参加活动或未参加活动");
                }
                if (joinInfo.getShareCount() == null) {
                    joinInfo.setShareCount(1);
                }else {
                    joinInfo.setShareCount(joinInfo.getShareCount()+1);
                }
                int update = joinInfoDao.update(joinInfo);
                HelpInfo helpInfo = helpInfoDao.queryAllByUIdAndAId(helpInfoDto.getAId(),userDto.getId());//查询是否助力过该用户
                if (helpInfo != null) {
                    return Result.failure("您已为其他用户再次活动中助力,不能助力为此用户助力");
                }
                if (update > 0) {
                    helpInfo = new HelpInfo();
                    helpInfo.setAId(helpInfoDto.getAId());
                    HelpInfo duplicate = duplicate(helpInfo, joinInfo, userDto, userInfo);
                    helpInfoDao.insert(duplicate);
                    return Result.ok();
                }
                return Result.failure("助力失败，请重新助力");
            } catch (Exception e) {
                log.error("help:"+e.getMessage());
                return Result.failure("助力失败，请重新助力");
            }
        }
        return Result.ok();
    }
    /**
     * 抽取共同代码
     * @param helpInfo
     * @param joinInfo
     * @param userDto
     * @param userDto1
     * @return
     * @throws Exception
     */
    private HelpInfo duplicate(HelpInfo helpInfo,JoinInfo joinInfo,UserDto userDto,UserInfo userDto1) throws Exception {
        helpInfo.setId(IdUtil.getStringId());
        helpInfo.setJId(joinInfo.getId());
        helpInfo.setHAddTime(DateUtils.getNowDate());
        helpInfo.setUName(userDto1.getNickName());
        helpInfo.setUId(userDto1.getId());
        helpInfo.setShareId(userDto.getId());
        helpInfo.setHNum(joinInfoService.getPrizeNum()); // 给助力用户分配中奖号码
        helpInfo.setShareName(userDto.getNickName());
        helpInfo.setUNum(joinInfoService.getPrizeNum());//给被助力用户分配中奖号码
        return helpInfo;
    }
    /**
     * 用户查询助力人员名单
     * @param userDto
     * @param aId
     * @param type
     * @return
     */
    @Override
    public Result queryHelpedInfo(UserDto userDto , String aId, Integer type) {
        if (userDto.getId() == null) {
            List<NameHelpDto> nameHelpCountDtoList = new ArrayList<>();
            List<NameHelpCountDto> joinInfos = joinInfoDao.queryUsersByAidAndUid(aId, "");
            Map<String, List<NameHelpCountDto>> collect = joinInfos.stream().collect(Collectors.groupingBy(NameHelpCountDto::getuId));
            if (collect.size() > 0) {
                collect.entrySet().forEach(stringListEntry -> {
                    List<NameHelpCountDto> value = stringListEntry.getValue();
                    NameHelpDto nameHelpDto = new NameHelpDto();
                    nameHelpDto.setCount(value.size());
                    value.forEach(nameHelpCountDto -> {
                        String starString = StringUtils.getStarString(nameHelpCountDto.getTelphone(), 4, 8);
                        nameHelpCountDto.setTelphone(starString);
                    });
                    nameHelpDto.setNameHelpCountDtoList(value);
                    nameHelpCountDtoList.add(nameHelpDto);
                });
                return Result.ok().setData(nameHelpCountDtoList);
            }
            return Result.failure("没有助力人员名单");
        }
        List<NameHelpCountDto> joinInfos = joinInfoDao.queryUsersByAidAndUid(aId, userDto.getId());
        if (joinInfos.size()> 0) {
            joinInfos.forEach(nameHelpCountDto -> {
                String starString = StringUtils.getStarString(nameHelpCountDto.getTelphone(), 3, 7);
                nameHelpCountDto.setTelphone(starString);
            });
            NameHelpDto nameHelpDto = new NameHelpDto();
            nameHelpDto.setCount(joinInfos.size());
            nameHelpDto.setNameHelpCountDtoList(joinInfos);
            return Result.ok().setData(nameHelpDto);
        }
        return Result.failure("未查询到信息，请刷新页面");
    }

    /**
     * 用户查询自己在某活动中助理过的所有用户
     * @param userId
     * @param jid
     * @return
     */
    @Override
    public Result queryHelpInfo(String userId, String jid) {
        HelpInfo helpInfo=new HelpInfo();
        helpInfo.setShareId(userId);
        helpInfo.setJId(jid);
        List<HelpInfo> helpInfos = helpInfoDao.queryAll(helpInfo);
        List<HelpInfoDto> helpInfoDtos = ModelMapperUtil.strictMapList(helpInfos, HelpInfoDto.class);
        return Result.ok().setData(helpInfoDtos);
    }

    /**
     * 查询用户在某一个活动下的所有助力信息(帮别人助力和别人帮自己助力的数据)
     * @param aid
     * @return
     */
    @Override
    public List<HelpInfoDto> queryHelpInfosOfActivity(String aid,String userId) {
        List<HelpInfo> helpInfos = helpInfoDao.queryHelpInfosOfActivity(aid,userId);
        return null;
    }

    /**
     * 用户查询某活动下拥有的抽奖号
     * @param userDto
     * @param aId
     * @param type
     * @return
     */
    @Override
    public Result queryHelpedPrizeNumInfo(UserDto userDto, String aId, Integer type) {
        JoinInfo joinInfo = joinInfoDao.queryAllByUIdAndAId(userDto.getId(), aId);
        HelpInfo helpInfo = new HelpInfo();
        helpInfo.setJId(joinInfo.getId());
        helpInfo.setUId(userDto.getId());
        List<HelpInfo> helpInfos = helpInfoDao.queryAll(helpInfo);
        List<HelpInfoDto> hashMaps = ModelMapperUtil.strictMapList(helpInfos, HelpInfoDto.class);
        return Result.ok().setData(hashMaps);
    }
}
